// src/composables/useQuestionnaire.ts
import { ref, reactive, toRefs, onMounted } from 'vue';
import { listQuestionnaire, getQuestionnaire, delQuestionnaire, addQuestionnaire, updateQuestionnaire } from '@/api/system/questionnaire';
import { QuestionnaireVO, QuestionnaireQuery, QuestionnaireForm } from '@/api/system/questionnaire/types';

export function useQuestionnaire() {
  const { proxy } = getCurrentInstance() as ComponentInternalInstance;

  const questionnaireList = ref<QuestionnaireVO[]>([]);
  const buttonLoading = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref<Array<string | number>>([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);

  const queryFormRef = ref<ElFormInstance>();
  const questionnaireFormRef = ref<ElFormInstance>();

  const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
  });

  const initFormData: QuestionnaireForm = {
    id: undefined,
    title: undefined,
    result: undefined
  };

  const data = reactive<PageData<QuestionnaireForm, QuestionnaireQuery>>({
    form: { ...initFormData },
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      title: undefined,
      result: undefined,
      params: {}
    },
    rules: {
      id: [{ required: true, message: '主键id不能为空', trigger: 'blur' }],
      title: [{ required: true, message: '问卷标题不能为空', trigger: 'blur' }],
      result: [{ required: true, message: '返回结果不能为空', trigger: 'blur' }]
    }
  });

  const { queryParams, form, rules } = toRefs(data);

  const getList = async () => {
    loading.value = true;
    const res = await listQuestionnaire(queryParams.value);
    questionnaireList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  };

  const cancel = () => {
    reset();
    dialog.visible = false;
  };

  const reset = () => {
    form.value = { ...initFormData };
    questionnaireFormRef.value?.resetFields();
  };

  const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
  };

  const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
  };

  const handleSelectionChange = (selection: QuestionnaireVO[]) => {
    ids.value = selection.map((item) => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  };

  const handleAdd = () => {
    reset();
    dialog.visible = true;
    dialog.title = '添加问卷';
  };

  const handleUpdate = async (row?: QuestionnaireVO) => {
    reset();
    const _id = row?.id || ids.value[0];
    const res = await getQuestionnaire(_id);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = '修改问卷';
  };

  const submitForm = () => {
    questionnaireFormRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        buttonLoading.value = true;
        if (form.value.id) {
          await updateQuestionnaire(form.value).finally(() => (buttonLoading.value = false));
        } else {
          await addQuestionnaire(form.value).finally(() => (buttonLoading.value = false));
        }
        proxy?.$modal.msgSuccess('操作成功');
        dialog.visible = false;
        await getList();
      }
    });
  };

  const handleDelete = async (row?: QuestionnaireVO) => {
    const _ids = row?.id || ids.value;
    await proxy?.$modal.confirm('是否确认删除问卷编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
    await delQuestionnaire(_ids);
    proxy?.$modal.msgSuccess('删除成功');
    await getList();
  };

  const handleExport = () => {
    proxy?.download(
      'system/questionnaire/export',
      {
        ...queryParams.value
      },
      `questionnaire_${new Date().getTime()}.xlsx`
    );
  };

  onMounted(() => {
    getList();
  });

  return {
    questionnaireList,
    buttonLoading,
    loading,
    showSearch,
    ids,
    single,
    multiple,
    total,
    queryFormRef,
    questionnaireFormRef,
    dialog,
    queryParams,
    form,
    rules,
    getList,
    cancel,
    reset,
    handleQuery,
    resetQuery,
    handleSelectionChange,
    handleAdd,
    handleUpdate,
    submitForm,
    handleDelete,
    handleExport
  };
}
